import React from 'react';
import { Card, Button, Form, Row, Col, Input, Divider, Modal, message } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import SimpleTable from '@/components/SimpleTable';

import $api from '@/api';
import MenuActionModal from './MenuActionModal';
import styles from './style.less';

const FormItem = Form.Item;

const titleMap = { Add: '添加', Edit: '修改' };

@Form.create()
export default class MenuList extends React.PureComponent {
  state = {
    loading: false,
    data: {
      list: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
    },
    record: undefined,
    modalAction: '',
    visible: false,
    menuList: [],
    submitting: false,
  };

  columns = [
    { title: 'ID', dataIndex: 'id' },
    { title: '名称', dataIndex: 'name' },
    { title: '编号', dataIndex: 'code' },
    { title: '上级菜单', dataIndex: 'parentName' },
    {
      title: '操作',
      dataIndex: '_op',
      render: (val, record, index) => (
          <>
            <a onClick={() => this.handleModalVisible(true, record, 'Edit')}>修改</a>
            <Divider type="vertical" /><a style={{ color: 'red' }} onClick={() => this.handleDelete(record)}>删除</a>
          </>
        ),
    },
  ];

  componentDidMount() {
    this.handleSearch();
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  };

  handleSearch = (params = {}) => {
    const { data: { pageNo, pageSize } } = this.state;
    const { form } = this.props;
    this.setState({ loading: true });
    form.validateFields((errors, values) => {
      if (errors) {
        return;
      }
      $api.menu.findPage({ pageNo, pageSize, ...values, ...params })
        .then(resp => {
          if (resp.code === 0) {
            this.state.data = resp.data;
          }
          this.setState({ loading: false })
        })
    });
  };


  handleModalVisible = (visible, record, action) => {
    if (visible) {
      if (action === 'Add' || action === 'Edit') {
        $api.menu.findList({ parentId: 0 })
          .then(resp => {
            if (resp.code === 0) {
              this.setState({ menuList: resp.data });
            }
          })
      }
      this.setState({ visible, record, modalAction: action })
    } else {
      this.setState({ visible, record: undefined, modalAction: '' })
    }
  };

  handleDelete = record => {
    Modal.confirm({
      title: '确认删除？',
      onOk: () => {
        $api.menu.remove(record.id)
          .then(resp => {
            if (resp.code === 0) {
              message.success('删除成功');
              this.handleSearch()
            }
          })
      },
    })
  };

  handleAdd = values => {
    this.setState({ submitting: true });
    $api.menu.add(values)
      .then(resp => {
        if (resp.code === 0) {
          message.success('保存成功');
          this.handleModalVisible(false);
          this.handleSearch()
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  handleEdit = values => {
    const { record } = this.state;
    this.setState({ submitting: true });
    $api.menu.edit(record.id, values)
      .then(resp => {
        if (resp.code === 0) {
          message.success('保存成功');
          this.handleModalVisible(false);
          this.handleSearch()
        }
      })
      .finally(() => this.setState({ submitting: false }))
  };

  renderForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form>
        <Row gutter={16}>
          <Col span={8}>
            <FormItem label="名称">
              {getFieldDecorator('name')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem label="编号">
              {getFieldDecorator('code')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col span={8}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.handleSearch({ pageNo: 1 })}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    )
  }

  render() {
    const { data, loading, modalAction, visible, record, menuList, submitting } = this.state;

    const actionProps = {
      visible,
      modalAction,
      menuList,
      confirmLoading: submitting,
      data: record,
      title: titleMap[modalAction],
      onOk: this[`handle${modalAction}`],
      onCancel: () => this.handleModalVisible(false),
    };

    return (
      <>
        <PageHeaderWrapper breadcrumb={false} title="菜单列表">
          <Card bordered={false}>
            <div className={styles.tableList}>
              <div className={styles.tableListForm}>{this.renderForm()}</div>
              <div className={styles.tableListOperator}>
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true, undefined, 'Add')}>
                  新建
                </Button>
              </div>
              <SimpleTable
                loading={loading}
                columns={this.columns}
                data={data}
                onChange={this.handleSearch}
              />
            </div>
          </Card>
        </PageHeaderWrapper>
        <MenuActionModal {...actionProps} />
      </>
    );
  }
}
